<template>
  <div class="test-question-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none">
      <div>
        <el-form inline>
          <el-form-item label="文件名称：" style="margin-bottom: 0">
            <el-input v-model="searchInfo.name" placeholder="请输入文件名称" />
          </el-form-item>
          <el-form-item style="margin-bottom: 0">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card shadow="never" style="border: none">
      <div class="header">
        <div class="header-warp">
          <div>
            <el-button
              text
              type="primary"
              icon="el-icon-upload"
              @click="uploadFile"
            >
              上传文件
            </el-button>
          </div>
        </div>
      </div>
      <div>
        <el-table
          v-loading="loading"
          row-key="id"
          style="width: 100%"
          :data="file"
          border
          :header-cell-style="{ background: '#F5F7FA' }"
        >
          <el-table-column prop="name" label="文件名称" align="center" />
          <el-table-column prop="type" label="文件类别" align="center" />
          <el-table-column
            label="最少阅读次数"
            prop="mini_num"
            align="center"
          />
          <el-table-column align="center" prop="action" label="操作">
            <template v-slot="{ row }">
              <el-button type="text" @click="preview(row)">查看</el-button>
              <el-button type="text" @click="downLoad(row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pages">
        <pagination
          style="margin-top: 0; padding-bottom: 0"
          :total="pageInfo.total"
          :limit="pageInfo.paginate"
          @pagination="pagination"
        />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="'上传文件'"
      width="600px"
      :close-on-click-modal="false"
      class="test-dialog"
    >
      <el-form
        ref="formRef"
        :model="fileForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <div class="btn-box">
          <div class="name">
            <el-form-item label="文件名称" prop="fileName">
              <el-input
                v-model="fileForm.fileName"
                placeholder="请输入文件名称"
              />
            </el-form-item>
            <el-form-item label="最少阅读次数" prop="fileNumber">
              <el-input
                v-model="fileForm.fileNumber"
                type="number"
                placeholder="请输入每人最少阅读次数"
              />
            </el-form-item>
            <el-form-item label="上传文件" prop="path">
              <el-input v-if="false" v-model="fileForm.path" />
              <el-upload
                class="upload-demo"
                :action="baseUrl + 'api/v1/upload/file'"
                :on-success="handleSuccess"
                :before-upload="beforeAvatarUpload"
                :on-remove="handleRemove"
                :limit="1"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          class="del-button"
          type="primary"
          @click="submitFile('formRef')"
        >
          提交
        </el-button>
      </span>
    </el-dialog>
    <div>
      <el-dialog
        :visible.sync="studyDocuments"
        :close-on-click-modal="false"
        :scrollable="false"
        width="60%"
        @close="headenClose"
      >
        <pdf
          ref="pdf"
          style="height: 55vh; overflow: auto"
          :src="documents"
          class="dialog-content"
          :page="pageNum"
          @progress="loadedRatio = $event"
          @num-pages="pageTotalNum = $event"
        />
        <div slot="footer" class="dialog-footer">
          <div class="page" style="margin-top: 10px; color: #409eff">
            {{ pageNum }} / {{ pageTotalNum }}
          </div>
          <div class="btnUD">
            <el-button
              round
              type="info"
              style="height: 30px; width: 80px; margin-right: 40px"
              size="mini"
              @click="prePage"
              >上一页</el-button
            >
            <el-button
              round
              type="info"
              style="height: 30px; width: 80px"
              size="mini"
              @click="nextPage"
              >下一页</el-button
            >
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { videosList, addContent } from "@/api/train";
import pdf from "vue-pdf";
import Pagination from "@/components/Pagination";
export default {
  components: {
    Pagination,
    pdf,
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      pageInfo: {
        paginate: 10,
        page: 1,
        total: 1,
      },
      searchInfo: {
        name: "",
      },
      file: [],
      isSubmitting: false,
      searchFileName: null,
      fileList: [],
      fileForm: {
        fileName: "",
        fileNumber: "",
        path: "",
      },
      rules: {
        fileName: [
          { required: true, message: "请输入文件名称", trigger: "blur" },
        ],
        fileNumber: [
          { required: true, message: "请输入文件阅读次数", trigger: "blur" },
        ],
        path: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      studyDocuments: false,
      documents: "",
      pageNum: 1, // 当前页
      pageTotalNum: 1, // 总页数
    };
  },
  created() {
    this.baseUrl = process.env.VUE_APP_UPLOAD;
    this.fileLists();
  },
  methods: {
    handleSearch() {
      this.pageInfo.page = 1;
      this.fileLists();
    },
    async fileLists() {
      this.loading = true;
      const params = {
        paginate: this.pageInfo.paginate,
        page: this.pageInfo.page,
        type: "pdf",
        name: this.searchInfo.name,
      };
      const res = await videosList(params);
      console.log(res, 111);
      this.file = res.data.data;
      this.pageInfo.total = res.data.total;
      this.loading = false;
    },
    cancel() {
      this.dialogVisible = false;
      this.fileForm.fileName = "";
      this.fileForm.fileNumber = "";
      this.fileForm.fileList = [];
    },
    async submitFile(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isSubmitting) {
            return;
          }

          this.isSubmitting = true;
          const data = {
            path: this.fileForm.path,
            name: this.fileForm.fileName,
            mini_num: this.fileForm.fileNumber,
          };
          addContent(data)
            .then((res) => {
              this.dialogVisible = false;
              this.fileList = [];
              this.fileForm.fileName = "";
              this.fileForm.fileNumber = "";
            })
            .catch(() => {
              this.isSubmitting = false;
            })
            .then(() => {
              this.fileLists();
              this.isSubmitting = false;
              this.$message({
                message: "上传文件成功",
                type: "success",
              });
            })
            .catch((err) => {
              this.isSubmitting = false;
              this.$message.error(err.response.data.message);
              console.log(err);
            });
        }
      });
    },
    pagination(e) {
      this.pageInfo.page = e.page;
      this.pageInfo.paginate = e.limit;
      this.fileLists();
    },
    uploadFile() {
      this.dialogVisible = true;
    },
    handleSuccess(file, fileList) {
      this.fileForm.path = file.data.path;
    },
    handleRemove(file, fileList) {
      this.fileForm.path = "";
      // this.fileForm.path = file.data.path
    },
    beforeAvatarUpload(file) {
      console.log(file.type);
      const isJPG = file.type === "application/pdf";

      if (!isJPG) {
        this.$message.error("上传协议文件只能是 pdf 格式!");
      }
      return isJPG;
    },
    preview(row) {
      this.documents = row.path;
      this.studyDocuments = true;
    },
    prePage() {
      let page = this.pageNum;
      page = page > 1 ? page - 1 : this.pageTotalNum;
      this.pageNum = page;
      this.scrollTopEvent();
    },

    // 下一页
    nextPage() {
      let page = this.pageNum;
      page = page < this.pageTotalNum ? page + 1 : 1;
      this.pageNum = page;
      this.scrollTopEvent();
    },
    downLoad(row) {
      window.location.href = row.path;
    },
    headenClose() {
      this.scrollTopEvent();
      this.pageNum = 1;
    },
    scrollTopEvent() {
      const dialogContent = document.querySelector(".dialog-content");
      // console.log(dialogContent.scrollTop,'dialogContent');
      if (dialogContent) {
        dialogContent.scrollTop = 0;
      }
    },
    reset() {
      this.pageInfo = this.$options.data().pageInfo;
      this.searchInfo = this.$options.data().searchInfo;
      this.fileLists();
    },
  },
};
</script>

<style scoped lang='scss'>
.test-question-list {
  padding: 20px;

  .header {
    display: flex;
  }

  .header-warp {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
  }
}
.footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialog-footer {
  text-align: center;
  .page {
    font-weight: 600;
    margin-bottom: 20px;
  }
  .btnUD {
    text-align: center;
  }
}
</style>
